<template>
  <div class="left_side">
    <!-- 下拉选择 -->
    <div class="form-select">
      <el-form :inline="true">
        <el-form-item label="">
          <el-select
            v-model="cityValue"
            size="large"
            placeholder="请选择城市"
            style="width: 300px"
            @change="selectCityChange"
            title="点击选择"
          >
            <el-option
              v-for="item in cityOptions"
              :key="item.code"
              :label="item.name"
              :value="item.code"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="">
          <el-select
            ref="selectRef"
            v-model="venueValue"
            :disabled="isDisabled"
            size="large"
            placeholder="请选择场馆"
            style="width: 300px"
            @visible-change="handleVenueVisibleChange"
            @change="selectVenueChange"
            title="点击选择"
            filterable
          >
            <el-option
              v-for="item in venueOptions"
              :key="item.Code"
              :label="item.Name"
              :value="item.Code"
            />
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="">
          <el-button type="" @click="onSearch">查询</el-button>
        </el-form-item> -->
      </el-form>
    </div>
    <!-- 卡片数据 -->
    <div class="data-card">
      <el-scrollbar>
        <el-card shadow="never">
          <div class="item-function">
            <div style="width: 50px">
              <img src="~assets/imgHome/leftMenueImg/hosp11079.png" alt="" />
            </div>
            <div class="power-text">定点医院</div>
            <div
              class="power-value power-value-hospi"
              @click="handShowHospital"
            >
              <span>{{ hospitalNumVx }}</span
              >&nbsp;所
            </div>
          </div>
        </el-card>
        <!-- <el-card shadow="never">
          <div class="item-function">
            <div style="width:50px;">
              <img src="~assets/imgHome/leftMenueImg/helicopter.png" alt="" />
            </div>
            <div class="power-text">直升机</div>
            <div class="power-value power-value-helicopter">
              <span>{{ 3 }}</span>&nbsp;架
            </div>
          </div>
        </el-card> -->
        <el-card shadow="never">
          <div class="item-function">
            <div style="width: 50px">
              <img
                src="~assets/imgHome/leftMenueImg/医疗点11260@2x.png"
                alt=""
              />
            </div>
            <div class="power-text">运动员村诊所</div>
            <div class="power-value">
              <span
                class="online-clas"
                @click="handShowMedicalRoom('MedicalPointType-4', 1)"
              >
                {{ athletesVillageClinicNumVx.onLine }}</span
              >
              /<span
                class="all-clas"
                @click="handShowMedicalRoom('MedicalPointType-4', 0)"
              >
                {{ athletesVillageClinicNumVx.total }}</span
              >&nbsp;个
            </div>
          </div>
        </el-card>
        <el-card shadow="never">
          <div class="item-function">
            <div style="width: 50px">
              <img
                src="~assets/imgHome/leftMenueImg/医疗点11260@2x.png"
                alt=""
              />
            </div>
            <div class="power-text">医务室</div>
            <div class="power-value">
              <span
                class="online-clas"
                @click="handShowMedicalRoom('MedicalPointType-1', 1)"
              >
                {{ medicalRoomNumVx.onLine }}</span
              >
              /<span
                class="all-clas"
                @click="handShowMedicalRoom('MedicalPointType-1', 0)"
              >
                {{ medicalRoomNumVx.total }}</span
              >&nbsp;个
            </div>
          </div>
        </el-card>
        <el-card shadow="never">
          <div class="item-function">
            <div style="width: 50px">
              <img
                src="~assets/imgHome/leftMenueImg/观众医疗点11259@2x.png"
                alt=""
              />
            </div>
            <div class="power-text">观众医疗点</div>
            <div class="power-value">
              <span
                class="online-clas"
                @click="handShowMedicalRoom('MedicalPointType-3', 1)"
              >
                {{ audienceMedicalNumVx.onLine }}</span
              >
              /<span
                class="all-clas"
                @click="handShowMedicalRoom('MedicalPointType-3', 0)"
              >
                {{ audienceMedicalNumVx.total }}</span
              >&nbsp;个
            </div>
          </div>
        </el-card>
        <el-card shadow="never">
          <div class="item-function">
            <div style="width: 50px">
              <img src="~assets/imgHome/leftMenueImg/FOP11258@2x.png" alt="" />
            </div>
            <div class="power-text">FOP医疗点</div>
            <div class="power-value">
              <span
                class="online-clas"
                @click="handShowMedicalRoom('MedicalPointType-2', 1)"
              >
                {{ FOPMedicalNumVx.onLine }}</span
              >
              /<span
                class="all-clas"
                @click="handShowMedicalRoom('MedicalPointType-2', 0)"
              >
                {{ FOPMedicalNumVx.total }}</span
              >&nbsp;个
            </div>
          </div>
        </el-card>
        <el-card shadow="never">
          <div class="item-function">
            <div style="width: 50px">
              <img src="~assets/imgHome/leftMenueImg/车11257@2x.png" alt="" />
            </div>
            <div class="power-text">救护车</div>
            <div class="power-value">
              <span class="online-clas" @click="handShowAmbulance(1)">{{
                ambulanceNumVx.onLine
              }}</span>
              /<span class="all-clas" @click="handShowAmbulance(0)">{{
                ambulanceNumVx.total
              }}</span
              >&nbsp;辆
            </div>
          </div>
        </el-card>
        <el-card shadow="never">
          <div class="item-function">
            <div style="width: 50px">
              <img src="~assets/imgHome/leftMenueImg/医生11256@2x.png" alt="" />
            </div>
            <div class="power-text">医生</div>
            <div class="power-value">
              <span class="online-clas" @click="handShowUserInfo(5, 1)">{{
                doctorNumVx.onLine
              }}</span>
              /<span class="all-clas" @click="handShowUserInfo(5, 0)">{{
                doctorNumVx.total
              }}</span
              >&nbsp;人
            </div>
          </div>
        </el-card>
        <el-card shadow="never">
          <div class="item-function">
            <div style="width: 50px">
              <img src="~assets/imgHome/leftMenueImg/护士11255@2x.png" alt="" />
            </div>
            <div class="power-text">护士</div>
            <div class="power-value">
              <span class="online-clas" @click="handShowUserInfo(6, 1)">{{
                nurseNumVx.onLine
              }}</span>
              /<span class="all-clas" @click="handShowUserInfo(6, 0)">{{
                nurseNumVx.total
              }}</span
              >&nbsp;人
            </div>
          </div>
        </el-card>
        <el-card shadow="never" class="drug_svg">
          <div class="item-function">
            <div style="width: 50px; margin-left: 10px">
              <img src="~assets/imgHome/leftMenueImg/drug11296@2x.png" alt="" />
            </div>
            <div class="power-text">药品耗材</div>
            <div class="power-value power-value-yphc">
              <el-progress
                type="circle"
                :percentage="mypercentage"
                :status="myprocessstatus"
                style="cursor: pointer"
                title="点击查看"
                @click="handleSurplus"
                :width="50"
                :stroke-width="3"
              >
              </el-progress>
            </div>
          </div>
        </el-card>
      </el-scrollbar>
    </div>

    <!-- 告警信息弹窗 -->
    <warnning class="warnning" />
  </div>
</template>

<script>
import {
  reactive,
  toRefs,
  onBeforeMount,
  onMounted,
  ref,
  watch,
  onBeforeUnmount,
  onUnmounted,
  inject,
} from 'vue';
import Warnning from './compChildMessage/Warnning';
import VueEvent from 'utils/event.js';
import {
  GetSubordinateCityCodeList,
  QueryVenue,
} from '../../../network/childCity';
import { GetDACInsufficient } from 'network/hosVenAmbuListData';

import { useStore } from 'vuex';
import { setupMapState } from '../../../store/utils/hook';

export default {
  name: 'LeftAside',
  components: { Warnning },
  props: {
    grugVenuesStatus: {
      type: Array,
    },
    DACRequestResLength: {
      type: Number,
    },
  },
  setup(props, ctx) {
    // console.log(props);
    const globalReload = inject('globalReload');
    const store = useStore();
    const selectRef = ref();
    const state = reactive({
      treeData: [],
      securityForces: ref({
        ensureVenueMedicalClinic: 0, //保障场馆医务室
        audienceMedicalPoint: 0, //观众医疗点
        FOPMedicalPoint: 0, //FOP医疗点
        ambulance: 0, //车辆数
        nurse: 0, //护士
        venueEnsureDoctor: 0, //场馆保障医生
        drugConsumption: 0, //药品消耗
      }),
      // 弹窗的显隐
      dialogVisible: ref(false),
      isShowHospitalDialog: ref(false),
      isShowAmbulanceDialog: ref(false),
      isShowVenueDialog: ref(false),
      isShowDrugConsumDialog: ref(false),

      // 药品耗材显示警告
      DACRequestRes: ref([]),
      mypercentage: ref(100),
      myprocessstatus: ref('success'),
      timer: 0,
      timerInterval: 0,

      //城市
      cityValue: -1,
      cityOptions: [],
      venueValue: -1,
      venueOptions: [{ Code: -1, Name: '--请选择--' }],
      venueOptionsCopy: [{ Code: -1, Name: '--请选择--' }],
      isDisabled: false,
    });
    // 根据人员的cityCode取显示城市的下拉
    const { ACVCodesVx } = setupMapState('app', ['ACVCodesVx']);
    const { userInfoVx } = setupMapState('app', ['userInfoVx']);
    const { hospitalTreeRemoteVxLength } = setupMapState('HospVenuAmbuModule', [
      'hospitalTreeRemoteVxLength',
    ]);

    const { athletesVillageClinicNumVx } = setupMapState('HospVenuAmbuModule', [
      'athletesVillageClinicNumVx',
    ]);
    const { audienceMedicalNumVx } = setupMapState('HospVenuAmbuModule', [
      'audienceMedicalNumVx',
    ]);
    const { FOPMedicalNumVx } = setupMapState('HospVenuAmbuModule', [
      'FOPMedicalNumVx',
    ]);
    const { medicalRoomNumVx } = setupMapState('HospVenuAmbuModule', [
      'medicalRoomNumVx',
    ]);
    const { ambulanceNumVx } = setupMapState('HospVenuAmbuModule', [
      'ambulanceNumVx',
    ]);
    const { doctorNumVx } = setupMapState('HospVenuAmbuModule', [
      'doctorNumVx',
    ]);
    const { nurseNumVx } = setupMapState('HospVenuAmbuModule', ['nurseNumVx']);
    const { hospitalNumVx } = setupMapState('HospVenuAmbuModule', [
      'hospitalNumVx',
    ]);

    const selectCityChange = async (val) => {
      // console.log(val)
      state.cityValue = val;
      state.venueValue = -1;
      // console.log(state.cityOptions)
      let findCity = state.cityOptions.find((item) => {
        return item.code == val;
      });
      // 保存cityName
      // console.log(findCity)
      // 保存选择的城市信息
      await store.dispatch('HospVenuAmbuModule/getFindCityInfo', {
        findCityInfo: findCity,
      });
      // 初始化场馆信息
      await store.dispatch('HospVenuAmbuModule/getFindVenueInfo', {
        findVenueInfo: { Code: -1, Name: '全部' },
      });
      // 缓存Code
      await store.dispatch('app/setACVCodes', {
        type: 'selectCity',
        cityCode: state.cityValue,
        venueCode: state.venueValue,
      });
      await globalReload();
    };
    // 场馆选项改变时触发
    const selectVenueChange = async (val) => {
      // console.log(val)
      state.venueValue = val;
      // console.log(state.venueOptions)
      let findVenue = state.venueOptions.find((item) => {
        return item.Code == val;
      });
      // console.log(findVenue)
      // 保存场馆信息
      await store.dispatch('HospVenuAmbuModule/getFindVenueInfo', {
        findVenueInfo: findVenue,
      });
      // 缓存Code
      await store.dispatch('app/setACVCodes', {
        type: 'selectVenue',
        cityCode: state.cityValue,
        venueCode: state.venueValue,
      });
      await globalReload();
    };
    // 场馆下拉打开时触发
    const handleVenueVisibleChange = async () => {
      // console.log("handleVenueVisibleChange", ACVCodesVx.value)
      // 取登陆时保存的人员城市code
      let activityCode = ACVCodesVx.value.activityCode;
      let userCode = userInfoVx.value.UserCode;
      let roleCode = userInfoVx.value.RoleCode;
      // 获取场馆
      await QueryVenue({
        ActivityCode: activityCode,
        CityCode: state.cityValue,
        UserCode: userCode,
        RoleCode: roleCode,
      })
        .then((res) => {
          // console.log(res)
          state.venueOptions = [{ Code: -1, Name: '--请选择--' }];
          if (res?.length > 0) {
            res.forEach((item) => {
              state.venueOptions.push(item);
            });
          }
        })
        .catch((err) => {
          console.log(err);
        });
    };
    // 查询
    const onSearch = () => {
      selectVenueChange(state.venueValue);
    };
    // 点击医院
    const handShowHospital = () => {
      // 子组件发射出事件，父组件中接收
      ctx.emit('handShowHospital');
    };
    // 点击场馆医务室/医疗点
    const handShowMedicalRoom = async (type, val) => {
      // await store.dispatch("HospVenuAmbuModule/getMedicalRoom", { type, venueId: state.venueValue })
      ctx.emit('showMedicalRoomEmit', { type, val });
    };
    // 点击医生:5、护士:6
    const handShowUserInfo = async (type, val) => {
      // await store.dispatch("HospVenuAmbuModule/getUserInfo", { type, venueId: state.venueValue })
      ctx.emit('showUserInfoEmit', { type, val });
    };
    // 点击车辆
    const handShowAmbulance = async (val) => {
      // console.log('val', val)
      // await store.dispatch("HospVenuAmbuModule/getAmbulanceInfo", { type: 1, venueId: state.venueValue })
      ctx.emit('showAmbulanceEmit', val);
    };
    const handShowVenue = () => {
      state.isShowVenueDialog = true;
      ctx.emit('handShowVenue', state.isShowVenueDialog);
    };
    const handleSurplus = () => {
      state.isShowDrugConsumDialog = true;
      ctx.emit('handleSurplus', state.isShowDrugConsumDialog);
    };
    // 请求数据
    const HandleDACRequest = async () => {
      try {
        // 判断是否选择了全部的场馆
        if (ACVCodesVx.value.venueCode == -1) {
          ACVCodesVx.value.venueCode = userInfoVx.value.venueCode;
        }
        state.DACRequestRes = await GetDACInsufficient(ACVCodesVx.value);
        // console.log(state.DACRequestRes);
        if (state.DACRequestRes['list3'].length > 0) {
          state.mypercentage = 30;
          state.myprocessstatus = 'exception';
          ctx.emit('sendDACRequestRes', state.DACRequestRes['list3']); //传到父组件
        } else if (state.DACRequestRes['list2'].length > 0) {
          state.mypercentage = 70;
          state.myprocessstatus = 'warning';
          ctx.emit('sendDACRequestRes', state.DACRequestRes['list2']); //传到父组件
        } else {
          state.mypercentage = 100;
          state.myprocessstatus = 'success';
          ctx.emit('sendDACRequestRes', state.DACRequestRes['list1']); //传到父组件
        }
      } catch (error) {
        throw error;
      }
    };
    watch(
      () => state.DACRequestRes.length,
      (neww, oldw) => {},
    );
    onBeforeMount(async () => {
      // 定时调用这个方法
      await HandleDACRequest();
      state.timer = setInterval(() => {
        HandleDACRequest();
      }, 1000 * 60); //分钟调一次 定时刷新药品耗材
    });
    onMounted(async () => {
      try {
        // 取登陆时保存的人员城市code（取城市下拉）
        let cityCode = userInfoVx.value.cityCode;
        let roleCode = userInfoVx.value.RoleCode;
        // 请求城市下拉
        await GetSubordinateCityCodeList({
          cityCode: cityCode,
          RoleCode: roleCode,
        })
          .then(async (res) => {
            // console.log(res)
            state.cityOptions = res;
            // console.log(ACVCodesVx)
            // 城市下拉框赋值选中的值（点击城市下拉会触发全局刷新，默认值取vuex中所保存的值）
            state.cityValue = Number(ACVCodesVx.value.cityCode);
            // 触发场馆下拉框事件，并初始赋值
            await handleVenueVisibleChange();
            // 赋值选中的值
            // console.log('ACVCodesVx.value.venueCode', ACVCodesVx.value.venueCode)
            if (
              ACVCodesVx.value.venueCode == null ||
              ACVCodesVx.value.venueCode == ''
            ) {
              state.venueValue = -1;
            } else {
              state.venueValue =
                ACVCodesVx.value.venueCode.toString().indexOf(',') == -1
                  ? Number(ACVCodesVx.value.venueCode)
                  : -1;
            }

            // 保存这个场馆的信息
            if (state.venueOptions.length > 0) {
              let findVenue = state.venueOptions.find((item) => {
                return item.Code == state.venueValue;
              });
              // console.log(findVenue)
              // 保存场馆信息
              await store.dispatch('HospVenuAmbuModule/getFindVenueInfo', {
                findVenueInfo: findVenue,
              });
            }
          })
          .catch((err) => {
            console.log(err);
          });
        //#region 左侧栏数量 定时刷新
        // 医疗点数量
        await store.dispatch('HospVenuAmbuModule/getMedicalCount', {
          venueId: state.venueValue,
        });
        // 车辆数量
        await store.dispatch('HospVenuAmbuModule/getAmbulanceCount', {
          venueId: state.venueValue,
        });
        // 人员数量
        await store.dispatch('HospVenuAmbuModule/getUserCount', {
          venueId: state.venueValue,
        });
        // 医院数量
        await store.dispatch('HospVenuAmbuModule/getHospitalCount');
        // 定时执行
        state.timerInterval = setInterval(async () => {
          // 医疗点数量
          await store.dispatch('HospVenuAmbuModule/getMedicalCount', {
            venueId: state.venueValue,
          });
          // 车辆数量
          await store.dispatch('HospVenuAmbuModule/getAmbulanceCount', {
            venueId: state.venueValue,
          });
          // 人员数量
          await store.dispatch('HospVenuAmbuModule/getUserCount', {
            venueId: state.venueValue,
          });
          // 医院数量
          await store.dispatch('HospVenuAmbuModule/getHospitalCount');
        }, 60000);

        //#endregion
      } catch (error) {
        clearInterval(state.timerInterval);
        throw error;
      }
    });

    onUnmounted(() => {
      console.log('map-left timer timerInterval定时器清除');
      clearInterval(state.timer);
      clearInterval(state.timerInterval);
    });
    const refState = toRefs(state);
    return {
      ...refState,
      hospitalTreeRemoteVxLength,
      athletesVillageClinicNumVx,
      audienceMedicalNumVx,
      FOPMedicalNumVx,
      medicalRoomNumVx,
      ambulanceNumVx,
      doctorNumVx,
      nurseNumVx,
      hospitalNumVx,
      ACVCodesVx,
      selectRef,
      handShowHospital,
      handShowVenue,
      handShowAmbulance,
      handleSurplus,
      selectCityChange,
      selectVenueChange,
      onSearch,
      handleVenueVisibleChange,
      handShowMedicalRoom,
      handShowUserInfo,
    };
  },
};
</script>
<style scoped>
.form-select {
  position: absolute;
  height: auto;
  width: 800px;
}

.data-card {
  width: 300px;
  margin-top: 50px;
}

.data-card .el-card {
  margin-top: 3px;
}

.data-card .item-function {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.item-function .power-text {
  width: 150px;
  font-family: Source Han Sans CN-Regular, Source Han Sans CN;
}

.item-function img {
  height: 30px;
  width: 30px;
}

/* .item-function .power-value:hover {
  cursor: pointer;
  color: #619af3;
} */
.item-function .power-value .online-clas:hover,
.item-function .power-value .all-clas:hover {
  cursor: pointer;
  color: #619af3;
}

.item-function .power-value-hospi span:hover {
  cursor: pointer;
  color: #619af3;
}

.item-function .power-value {
  width: 100px;
}

.item-function .power-value-yphc {
  line-height: 0;
}

:deep(.item-function .power-value .el-progress.is-warning .el-progress__text) {
  font-size: 16px !important;
}

.item-function .power-value span {
  font-size: 16px;
  font-weight: 500;
  font-family: Source Han Sans CN-Medium, Source Han Sans CN;
}

.warnning {
  position: fixed;
  right: 570px;
  top: 66px;
}

:deep(.el-card__body) {
  padding: 15px;
}

:deep(.drug_svg .el-card__body) {
  padding: 7px;
}

@media screen and (max-height: 820px) {
  .data-card {
    height: 375px;
  }
}
</style>
